package ku.cat;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import ku.cat.db.DatabaseHelper;
import ku.cat.db.model.AttendanceModel;
import ku.cat.db.model.StudentModel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

public class ClassAttendantActivity extends Activity {

	private static final String TAG = "CAT";

	private static final String COURSE_PREF_NAME = "COURSE_PREF";
	private SharedPreferences COURSE_PREF;

	// ClassAttendant camera;
	Preview preview;

	Button takePhoto;
	Button manKey;

	TextView stdNameTextView;
	TextView subjectNameTextView;
	TextView instruNameTextView;
	TextView stdTimeTextView;

	EditText nameText;

	StudentModel student;

	String picFileName;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// setContentView(R.layout.stdform);
		// setContentView(R.layout.proform);

		COURSE_PREF = getSharedPreferences(COURSE_PREF_NAME, 0);

		// setting preview screen
		preview = new Preview(this);
		((FrameLayout) findViewById(R.id.preview)).addView(preview);

		// handle button camera
		takePhoto = (Button) findViewById(R.id.buttonClick);
		takePhoto.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				// check student;
				if (student != null) {
					preview.camera.takePicture(shutterCallback, rawCallback,
							jpegCallback);

					// wait 5 sec to preview camera
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					// save to database
					AttendanceModel att = new AttendanceModel();
					att.setStudentrfid(student.getRfid());
					att.setClassid(COURSE_PREF.getString(Constants.course_id,
							"NA"));
					att.setFilename(picFileName);
					att.setReady(true);
					att.setUpload(false);

					att.setStamptime(new Date());

					DatabaseHelper db = new DatabaseHelper(
							getApplicationContext());
					db.addAttendance(att);

					preview.camera.startPreview();

					// release camera
					if (preview.camera != null) {
						preview.camera.stopPreview();
						preview.camera.release();
						preview.camera = null;
					}

				} else {
					AlertDialog.Builder alertError = new AlertDialog.Builder(
							getApplicationContext());

					alertError.setTitle("ผิดพลาด");
					alertError.setMessage("กรุณากรอกรหัสนักศึกษา");

					alertError.show();
				}

			}
		});

		// time
		stdTimeTextView = (TextView) findViewById(R.id.stdTime);
		stdTimeTextView.setText(new Date().toLocaleString());

		Log.d(TAG, "onCreate'd");
	}

	// FIXME manual key(forget card)
	public void manKey(View view) {
		Log.d(TAG, "manKey");

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("กรอกข้อมูล");
		alert.setMessage("กรอกรหัสนักศึกษา");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		alert.setView(input);

		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				Editable value = input.getText();

				// find student by code and map data
				DatabaseHelper db = new DatabaseHelper(getApplicationContext());
				student = db.getStudentFromId(value.toString());

				if (student != null) {
					stdNameTextView = (TextView) findViewById(R.id.stdName);

					stdNameTextView.setText(student.getFirstname() + " "
							+ student.getLastname());
					stdTimeTextView.setText(new Date().toLocaleString());
				} else {
					AlertDialog.Builder alertError = new AlertDialog.Builder(
							getApplicationContext());

					alertError.setTitle("ผิดพลาด");
					alertError.setMessage("ไม่พบนักศึกษา " + value);

					alertError.show();
				}

			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();
	}

	ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
			Log.d(TAG, "onShutter'd");
		}
	};

	/** Handles data for raw picture */
	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			Log.d(TAG, "onPictureTaken - raw");
		}
	};

	/** Handles data for jpeg picture */
	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			FileOutputStream outStream = null;
			try {
				// write to local sandbox file system
				// outStream =
				// CameraDemo.this.openFileOutput(String.format("%d.jpg",
				// System.currentTimeMillis()), 0);
				// Or write to sdcard
				Log.d(TAG, Environment.getExternalStorageDirectory().toString());

				picFileName = String.format(Environment
						.getExternalStorageDirectory().toString() + "/%s.jpg",
						new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
								.format(new Date()));

				outStream = new FileOutputStream(picFileName);

				outStream.write(data);
				outStream.flush();
				outStream.close();
				Log.d(TAG, "onPictureTaken - : " + data.length);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				Log.d(TAG, e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				Log.d(TAG, e.getMessage());
			} finally {
			}
			Log.d(TAG, "onPictureTaken - jpeg");
		}
	};

	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exit:
			finish();
			break;
		case R.id.instructor:

			// release camera
			if (preview.camera != null) {
				preview.camera.stopPreview();
				preview.camera.release();
				preview.camera = null;
			}

			// start instructor Activity
			startActivity(new Intent(this, InstructorActivity.class));

			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}